import axios from "axios";
import { refreshUsingPost } from "@/api/userController";
const request = axios.create({
  baseURL: "/api",
  timeout: 100000,
});

// 演示axios拦截器,拦截之前,发请求之前,可以再添加一些配置
request.interceptors.request.use(
  function (config) {
    // 添加请求头 获取token
    config.headers["accessToken"] = localStorage.getItem("accessToken");
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

//   返回来之后,可以添加一些东西,执行时间会比调用该方法后的.then()提前,
// @ts-ignore
request.interceptors.response.use(async (response) => {
  // 如果错误码为408
  if (response.data?.code === 40111) {
    // 发送刷新token请求
    const result = await refreshUsingPost({
      headers: {
        refreshToken: localStorage.getItem("refreshToken"),
      },
    });
    // 如果刷新成功,则更新token
    if (result.data?.code === 0) {
      localStorage.setItem("accessToken", result.data.data?.accessToken || "");
      localStorage.setItem(
        "refreshToken",
        result.data.data?.refreshToken || ""
      );
    }
    // 重新发送请求
    console.log(response.config);
    return request(response.config);
  } else if (response.data?.code === 0) {
    return response;
  } else if (response.data?.code === 40100) {
    // 如果错误码为40100,则跳转到登录页面
    window.location.href = "/user/login";
  } else {
    return Promise.reject("请求超时");
  }
});

export default request;
